//
//  AppDelegate.swift
//  XNWeiBo_Swift
//
//  Created by xunan on 16/6/18.
//  Copyright © 2016年 xunan. All rights reserved.
//

import UIKit

// 切换控制器通知
let XMGSwitchRootViewControllerKey = "XMGSwitchRootViewControllerKey"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        print(UserAccount.loadAccount())
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.switchRootViewController(_:)), name: XMGSwitchRootViewControllerKey, object: nil)
        
        application.statusBarStyle = UIStatusBarStyle.LightContent
        // 全局有效
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
        
        // 1.创建window
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        // 2.创建根控制器
        window?.rootViewController = defaultController()
        
        window?.makeKeyAndVisible()
        
        return true
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func switchRootViewController(notify: NSNotification) {
    
        if notify.object as! Bool {
            window?.rootViewController = MainViewController()
        } else {
            window?.rootViewController = WelcomeViewController()
        }
    }
    
    private func defaultController() -> UIViewController {
        if UserAccount.userLogin() {
            return isNewupdate() ? NewFeatureCollectionViewController() : WelcomeViewController()
        }
        return MainViewController()
    }
    
    
    private func isNewupdate() -> Bool {
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        
        let sandboxVersion = NSUserDefaults.standardUserDefaults().objectForKey("CFBundleShortVersionString") as? String ?? ""
        print("current = \(currentVersion) sandbox = \(sandboxVersion)")

        if currentVersion.compare(sandboxVersion) == NSComparisonResult.OrderedDescending
        {
            NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: "CFBundleShortVersionString")
        }
        
        return false
    }

  
}

